<template>
<div>
    <Modal
      v-model="visible"
      :mask-closable="false"
      width="600px"
      :title="title"
    >
      <Form :model="form" ref="roleForm" :rules="rules" :label-width="100">
        <FormItem label="角色名称"  prop="roleName">
          <Input v-model="form.roleName" placeholder="请输入角色名称" />
        </FormItem>
        <FormItem label="角色编码"  prop="roleCode">
          <Input v-model="form.roleCode"placeholder="按照Spring Security约定建议以‘ROLE_’开头"/>
        </FormItem>
        <FormItem label="数据权限" prop="dsType">
          <Select v-model="form.dsType">
            <Option v-for="item in dataScopeList" :value="item.id" :key="item.id">{{item.des}}</Option>
          </Select>
        </FormItem>
        <FormItem v-if="form.dsType===4" style="margin-top:15px">
          <div style="position:relative">
            <Tree :data="data" ref="deptTree" multiple style="margin-top:15px"></Tree>
          </div>
        </FormItem>
        <FormItem label="角色描述" prop="roleDesc">
          <Input type="textarea" v-model="form.roleDesc" :rows="4" placeholder="请输入个人简介" />
        </FormItem>
      </Form>
      <div class="demo-drawer-footer">
        <Button type="primary" style="margin-right: 8px" :loading="submitLoading" @click="submitForm">{{$t("submit")}}</Button>
        <Button  @click="close">{{$t("close")}}</Button>
      </div>
    </Modal>
</div>
</template>

<script>
import {getDeptTree} from "@/api/dept";
import {addRole,updateRole} from "@/api/role";
export default {
  name: "RoleForm",

  data(){
    return{
      styles: {
        height: 'calc(100% - 55px)',
        overflow: 'auto',
        paddingBottom: '53px',
        position: 'static'
      },
      data:[],
      visible:false,
      treeLoading:false,
      title:'添加',
      submitLoading:false,
      form:{
        roleName:'',
        roleCode:'',
        roleDesc:'',
        dsType:1,
      },
      modalType:1,
      deptIdList:[],
      dataScopeList:[
        {
          id: 1,
          des: '全部'
        },
        {
          id: 2,
          des: '本级'
        },
        {
          id: 3,
          des: '本级以及子级'
        },
        {
          id: 4,
          des: '自定义'
        }
      ],
      rules:{
        roleName: [
          {required:true,message:'请输入角色名称',trigger:'blur'},
          { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' }
        ],
        roleCode: [
          {required:true,message:'请输入角色编码',trigger:'blur'}
        ],
        dsType:[
          {type:'number',required:true,message:'请选择数据权限',trigger:'change'}
        ]
      }
    }
  },
  methods:{
    add(){
      this.edit({})
    },
    edit(record){
      if(Object.keys(record).length!=0){
        this.deptIdList=record.roleDepts;
        let deptIds=record.roleDepts;
        this.form=record;
        this.form.roleId=record.roleId;
        this.checkDeptTree(this.data,deptIds)
      }
      this.visible=true;
    },
    checkDeptTree(permData, rolePerms) {
      let that = this;
      permData.forEach(function(p) {
        if (that.hasDeptSelected(p, rolePerms)) {
          that.$set(p,'selected',true)
        } else {
          that.$set(p,'selected',false)
        }
        if (p.children && p.children.length > 0) {
          that.checkDeptTree(p.children, rolePerms);
        }
      });
    },
    // 判断角色拥有的权限节点勾选
    hasDeptSelected(p, rolePerms) {
      let flag = false;
      for (let i = 0; i < rolePerms.length; i++) {
        if (p.deptId == rolePerms[i]) {
          flag = true;
          break;
        }
      }
      if (flag) {
        return true;
      }
      return false;
    },
    close(){
      this.visible=false;
      this.deptIdList=[];
      // this.$refs['roleForm'].resetFields();
    },
    submitForm(){
      let that=this;
      that.$refs['roleForm'].validate((valid)=>{
        if(valid){
          that.submitLoading=true;
          if(that.form.dsType===4){
            let nodes = that.$refs['deptTree'].getSelectedNodes();
            console.log(nodes)
            let deptIds=[];
            for(let item of nodes){
               deptIds.push(item.deptId);
            }
            that.form.roleDepts=deptIds;
            let obj;
            if(that.modalType===1){
               obj=addRole(that.form);
            }else{
              obj=updateRole(that.form);
            }
            obj.then(res=>{
              if(res.code===200){
                that.submitLoading=false;
                that.$Message.success('操作成功');
                that.close();
                that.$emit('ok')
              }
              that.submitLoading=false;
            }).catch((error)=>{
              console.log(error);
              that.submitLoading=false;
            }).finally(()=>{
              that.submitLoading=false;
            })
          }
        }
      })
    },
    initDeptData(){
      this.treeLoading=true;
      getDeptTree().then(res=>{
        if(res.code===200){
           this.data=res.data;
           this.treeLoading=false;
        }
      })
    }
  },
  mounted(){
    this.initDeptData()
  }
}
</script>

<style scoped>
.demo-drawer-footer{
  width: 100%;
  position: absolute;
  bottom: 0;
  left: 0;
  border-top: 1px solid #e8e8e8;
  padding: 10px 16px;
  text-align: right;
  background: #fff;
}
</style>
